package com.sw.small_world.utils;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;


import com.sw.small_world.fragment.base.BaseFragment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 对bitmap的一些操作
 * Created by zs on 2016/3/25.
 */
public class BitmapUtils {


    /**
     * 旋转图片
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        ;
        matrix.postRotate(angle);
        //System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }


    /**
     * 裁剪图片固定才成200*200大小的图片
     */
    public static void cutPhoto(BaseFragment fragment, Uri uri, boolean isHeadPic) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        if (isHeadPic) {
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);

            intent.putExtra("scale", true);
            //只能设置成false，k920无法返回
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(FileUtils.getHeadPhotoCutFile()));
            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
            intent.putExtra("noFaceDetection", true);
        } else {
            // 是否保留比例
            intent.putExtra("scale", "true");
        }
        fragment.startActivityForResult(intent, ConstantUtils.ACTIVITY_CUT_IMAGE_REQUEST_CODE);
    }


    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /**
     * 指定压缩大小保存bitmap进file的工具方法
     *
     * @param path     想要保存的图片文件路径
     * @param compress 想要压缩的大小,填写0到100,100为不压缩
     * @param bitmap   想要转换的bitmap图片
     */


    public static void saveBitmapToFile(String path, int compress, Bitmap bitmap) {
        File f = new File(path);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(f));
            bitmap.compress(Bitmap.CompressFormat.JPEG, compress, bos);
            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void saveJpg(InputStream is, String dir) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String fileName = format.format(new Date(System.currentTimeMillis()));
        File f = new File(dir, fileName);
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(f));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Bitmap compressBitmapFromFile(String path, int reqHeight, int reqWidth) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = true;
        int ratio = calculateOptions(reqHeight, reqWidth, options);


        return bitmap;
    }


    /**
     * 传入想要压缩的bitmap的宽高和对应的需要压缩的bitmap的options,返回一个压缩比例.
     *
     * @param reqHeight 想要压缩后的高度
     * @param reqWidth  想要压缩后的宽度
     * @param options   对应bitmap的options
     * @return 一个压缩比例
     */

    public static int calculateOptions(int reqHeight, int reqWidth, BitmapFactory.Options options) {
        //如果需求的宽和高都大于实际的了,那么久不压缩
        int width = options.outWidth;
        int height = options.outHeight;
        if (reqHeight > height && reqWidth > width) {
            return 1;
        } else {
            //得到计算的比例
            int widthSize = width / reqWidth;
            int heightSize = height / reqHeight;
            return widthSize > heightSize ? widthSize : height;
        }

    }
}
